
var choice_menu_html = `<form id="choice-menu">
<label title="时间默认为00:00:00">开始日期<input type="date" name="startdate" required></label>
<label title="时间默认为23:00:00">结束日期<input type="date" name="enddate"></label>
<label>团队<input type="text" name="deptName"></label><br>
<label>任务名称<input type="text" name="taskName"></label>
<label>接通状态<select name="isConn">
    <option value=""></option>
    <option value="1">已接通</option>
    <option value="0">未接通</option>
</select></label>
<label>被叫号码<input type="text" name="phone"></label><br>
<label>意向<select name="handleResult">
    <option value=""></option>
    <option value="agree">同意</option>
    <option value="refuse">拒绝</option>
</select></label>
<label id="totalRows">查询结果：</label>
<label><button id="goToBefore" type="button">三月前</button>
<button class="download" type="button">下载</button>
<button class="search" type="button">查询</button></label>
</form>`



//left-menu点击事件
$(document).on("click",".left-menu1",function(){
    // 执行对应的方法
    var fn = $(this).toggleClass("collapsed");
});

// 定义date对象的format方法
Date.prototype.format = function(format){
    var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
    RegExp.$1.length==1 ? o[k] :
    ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
};

// 加载动画
function loading_img(state='',msg=''){
    if(state=='load'){
        $('#beyondShow').html('<h5>'+msg+'</h5><img><br><span id="hide-load">卡死？</span>');
        $('#beyondShow').show();
    }else{
        $('#beyondShow').html('');
        $('#beyondShow').hide();
    };
};
// 卡死后删除
$(document).on("click","#hide-load",function(){
    loading_img();
});

// 设置
function getInfo(name,h2_name){
    $("#rightShow").html('<h2>'+h2_name+'</h2><table id="LoginLog"></table>');
    // $(".left-bar-menu").nextAll().remove();
    $.getJSON("/api/get"+name,function(json){
        var html = '<tr><th>set</th>';
        $.each(json.data[0], function(index,value){
            html += '<th>'+index+'</th>';
        });
        html += '</tr>';
        $.each(json.data, function(index,value){
            html += '<tr><td><a class="set" name="'+name+'" key="'+value.key+'">🔧</a></td>';
            $.each(value, function(index,value){
                html += '<td>'+value+'</td>';
            });
            html += '</tr>';
            $("#LoginLog").html(html);
        });
    });
};
// 获取单个vars
$(document).on("click",".set",function(){
    $("#beyondShow").html('').show();
    var name = $(this).attr("name");
    var key = $(this).attr("key");
    var html = '<ul><form id="config">';
    $.getJSON("/api/get"+name,{"key":key},function(json){
        $.each(json.data, function(index,value){
            html += '<lable>'+index+'</lable>';
            html += '<li><input name="'+index+'" value="'+value+'"></li>';
        });
        html += '</form><br><li><button id="up-sub" name="'+name+'">更新</button>&nbsp;&nbsp;&nbsp;';
        html += '<button id="ins-sub" name="'+name+'">新增</button>&nbsp;&nbsp;&nbsp;';
        html += '<button id="del-sub" name="'+name+'">删除</button></li><br></ul>';
        $("#beyondShow").html(html);
    });
});
// 更新
$(document).on("click","#up-sub",function(){
    var name = $(this).attr("name");
    var formdata = {};
    $.each($("#config").serializeArray(),function(index,value){
        formdata[value.name] = value.value;
    });
    $.getJSON("/api/up"+name,formdata,function(json){
        if(json.state=='ok'){
            $('#beyondShow').html('').hide();
            getInfo(name);
        }else{
            alert(name+'【更新操作】遇到了问题！');
        };
    });
});
// 删除
$(document).on("click","#del-sub",function(){
    var name = $(this).attr("name");
    var res = confirm('确认删除此条【'+name+'】吗？不可恢复！！！');
    if(res == true){
        var formdata = {};
        $.each($("#config").serializeArray(),function(index,value){
            formdata[value.name] = value.value;
        });
        $.getJSON("/api/del"+name,formdata,function(json){
            if(json.state=='ok'){
                $('#beyondShow').html('').hide();
                getInfo(name);
            }else{
                alert(name+'【删除操作】遇到了问题！');
            };
        });
    };
});
// 新增
$(document).on("click","#ins-sub",function(){
    var name = $(this).attr("name");
    var formdata = {};
    $.each($("#config").serializeArray(),function(index,value){
        formdata[value.name] = value.value;
    });
    $.getJSON("/api/ins"+name,formdata,function(json){
        if(json.state=='ok'){
            $('#beyondShow').html('').hide();
            getInfo(name);
        }else{
            alert(name+'【新增操作】遇到了问题！');
        };
    });
});


// 查询&下载
function callReport(){
    $("#rightShow").html('<h2>外呼明细查询&下载</h2>'+choice_menu_html);
    $('#rightShow').append('<table id="callReport"></table>');
    var start_time = new Date();
    // start_time.setDate(start_time.getDate()-60);
    $('#choice-menu input[name="startdate"]').val(start_time.format('yyyy-MM-dd'));//初始化开始时间
    $('#choice-menu .search').attr('id', 'showCallReport');
    $('#choice-menu .download').attr('id', 'downLoadCallReport');
};
// 外呼明细
$(document).on("click","#showCallReport",function(){
    $("#callReport").html('<tr><th>时间</th><th>被叫号码</th><th>团队</th><th>主叫</th><th>任务名</th><th>通话时长</th><th>意向</th><th>坐席</th><th>产品</th><th>备注</th><th>录音</th></tr>');
    var totalRows = 0;
    var num = $("#team-list :checked").length;
    if(num>0){
        loading_img('load','查询中～');
    };
    $("#team-list :checked").each(function(){
        sub_data = getChoiceValues();
        sub_data['city_id'] = $(this).attr('id');
        $.getJSON("/api/searchphone",sub_data,function(json){
            $.each(json.data, function(index,value){
                var r = value;
                var html = '<tr><td>'+r.createTime+'</td><td>'+r.called+'</td><td>'+r.deptName+'</td>\
                <td>'+r.calling+'</td><td>'+r.taskName+'</td><td>'+r.contactLength1+'</td><td>'+r.handleResult+'</td>\
                <td>'+r.userName+'</td><td>'+r.productName+'</td><td>'+r.remark+'</td>';
                if(r.recordFile == ""){
                    html += '<td></td></tr>';
                }else{
                    html += '<td><a hidden>'+r.recordFile+'\t</a><a href="'+r.recordFile+'" target="_blank">点击下载</a></td></tr>';
                };
                $("#callReport").append(html);
            });
            totalRows += json.totalRows;
            $("#totalRows").html('获取到'+String(totalRows)+'条记录');
            num -= 1;
            if(num==0){
                loading_img();
            };
        });
    });
});
// 三月前
$(document).on("click","#goToBefore",function(){
    var start_time = new Date();
    start_time.setDate(start_time.getDate()-59);
    $('#choice-menu input[name="startdate"]').val(start_time.format('yyyy-MM-dd'));//初始化开始时间
});
// 下载
$(document).on("click","#downLoadCallReport",function(){
    $("#callReport").html('<tr><th>摘要</th><th>文件位置</th><th>大小</th><th>下载状态</th></tr>');
    $("#team-list :checked").each(function(){    
        var sub_data = getChoiceValues();
        sub_data['city_id'] = $(this).attr('id');
        var remark = $(this).parent().text();
        $.each(sub_data,function(index,value){
            remark += '&'+index+'='+value;
        });
        sub_data['remark'] = remark;
        $("#callReport").append('<tr class="download-tr"><td href="'+remark+'">'+remark+'</td><td></td><td></td>><td><img class="loading"</td>');
        $.getJSON("/api/report/downloadreport",sub_data,function(json){
            $('.download-tr td[href="'+remark+'"]').parent().find('td:eq(1)').html(json.data.exl_path);
            $('.download-tr td[href="'+remark+'"]').parent().find('td:eq(2)').html(json.data.exl_size);
            $('.download-tr td[href="'+remark+'"]').parent().find('td:eq(3)').html('<a class="openexl" name="'+json.data.exl_path+json.data.file_name+'">📂</a>');
        });
    });
});
// 点击打开
$(document).on("click",".openexl",function(){
    var exl_path = $(this).attr('name');
    var o_path = $(this).attr('o_path');
    if(o_path){
        $.getJSON("/api/report/openexl",{"exl_path":o_path},function(){}).fail(function(){
            alert(o_path+'  打开失败！');
        });
    }else{
        $.getJSON("/api/report/openexl",{"exl_path":exl_path,"is_path":true},function(){}).fail(function(){
            alert(exl_path+'  打开失败！')
        });
    };
});

// 任务情况
function showTask(){
    $("#rightShow").html('<h2>任务情况</h2><button>刷新</button> \
    <table id="taskInfo"></table>');
    $("#taskInfo").html('<tr><th>任务</th><th><select name="teamname" id="task-teamn"><option value="">全部</option></select></th><th>创建时间</th><th>总量</th> \
    <th>完成量</th><th>剩余量</th><th>完成百分比</th><th><select name="tasktype" id="task-type"><option value="">全部</option></select></th></tr>');
    var num = $("#team-list :checked").length;
    if(num>0){
        loading_img('load','查询中～');
    };
    $(".loading-bg").show();
    $.getJSON("/api/gettaskinfo",function(json){
        $.each(json.data, function(index,value){
            var html='<tr>';
            $.each(value, function(index,value){
                html+='<td>'+value+'</td>';
            });
            html+='</tr>';
            $("#taskInfo").append(html);
        });
        num -= 1;
        if(num==0){
            loading_img();
        };
    });
};
// 任务情况-实时
function getTask(){
    $("#rightShow").html('<h2>任务情况-实时</h2><table id="taskInfo"></table>');
    $("#taskInfo").html('<tr><th>任务</th><th>团队</th><th>创建时间</th><th>总量</th><th>完成量</th><th>剩余量</th><th>完成百分比</th><th>项目类型</th></tr>');
    var num = $("#team-list :checked").length;
    if(num>0){
        loading_img('load','查询中～');
    };
    $("#team-list :checked").each(function(){
        var city_id = $(this).attr('id');
        $(".loading-bg").show();
        $.getJSON("/api/gettask",{"key":city_id},function(json){
            $.each(json.data, function(index,value){
                var html='<tr>';
                $.each(value, function(index,value){
                    html+='<td>'+value+'</td>';
                });
                html+='</tr>';
                $("#taskInfo").append(html);
            });
            num -= 1;
            if(num==0){
                loading_img();
            };
        });
    });
};
// 任务计划
function exTask(is_up){
    $("#rightShow").html('<h2>团队任务情况<button id="up-task">更新</button></h2><div id="team-taskifno"></div>');
    if (is_up) {
        var get_key = is_up;
    } else {
        var get_key = '';
    };
    $.getJSON("/api/getteamtaskinfo",{"key":get_key},function(json){
        var taskTypeDic = {};
        $.each(json.data, function(index,value){
            if (taskTypeDic.hasOwnProperty(value.used_team)) {
                var remark = 0;
                for (var key in taskTypeDic[value.used_team]){
                    if (taskTypeDic[value.used_team][key][0] == value.city_name && taskTypeDic[value.used_team][key][1] == value.type) {
                        taskTypeDic[value.used_team][key][2] = taskTypeDic[value.used_team][key][2] + parseInt(value.leftNum);
                        remark = 1;
                    };
                };
                if (remark == 0) {
                    taskTypeDic[value.used_team].push([value.city_name,value.type,parseInt(value.leftNum),value.upDate]);
                }
            } else {
                taskTypeDic[value.used_team] = [[value.city_name,value.type,parseInt(value.leftNum),value.upDate]];
            };
            // $("#team-taskifno").append(value.taskName + '<br>');
        });
        for (var key in taskTypeDic){
            $("#team-taskifno").append('<br><p>' + key + ' 的剩余数据分布：<br>(' + taskTypeDic[key][0][3] + ')</p>');
            for (var v in taskTypeDic[key]){
                var html = '<p class="task-jh-input">' + String(taskTypeDic[key][v].slice(0,3)) + ',';
                // html += '<span>计划</span>\
                // <select name="jh" class="">\
                //     <option value=""></option>\
                //     <option value="wh">外呼</option>\
                //     <option value="cd">成单</option>\
                // </select>\
                // <input type="text" name=""></p>';
                $("#team-taskifno").append(html);
            };
        };
        $("#team-taskifno").append('<button id="up-task-jh">计划</button><div id="jh"></div>');
        loading_img();
    });
};
// 
$(document).on("click","#up-task-jh",function(){
    $("#jh").append($(".task-jh-input").text());
});
// 更新团队任务情况
$(document).on("click","#up-task",function(){
    loading_img('load','执行中～');
    exTask('up');
});


// 每日告警
$(document).on("click","#gj-sub",function(){
    loading_img('load','执行中～');
    $.getJSON("/api/report/gj",function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 监控表
$(document).on("click","#jk-sub",function(){
    var city_ids = '';
    var now_date = $('#jk-date').val();
    // var jk_output = config_vars.jk_output;
    $("#team-list :checked").each(function(){
        city_ids += '#' + $(this).attr('id');
    });
    // console.log({"now_date":now_date,"jk_output":jk_output,"team_list":city_ids});
    loading_img('load','执行中～');
    $.getJSON("/api/report/jk",{"now_date":now_date,"team_list":city_ids},function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 监控（快速）
$(document).on("click","#quickjk-sub",function(){
    loading_img('load','执行中～');
    $.getJSON("/api/report/ljk",function(json){
        // echarts();
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 撸开户
$(document).on("click","#lkh-sub",function(){
    loading_img('load','执行中～');
    $.getJSON("/api/report/lkh",function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 撸开户-更新日报中开户情况
$(document).on("click","#lkh-updayreport",function(){
    loading_img('load','执行中～');
    $.getJSON("/api/report/lkh",{'updayreport':true},function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 增量更新
$(document).on("click","#upcallreport-sub",function(){
    var now_date = $('#upcallreport-date').val();
    loading_img('load','执行中～');
    $.getJSON("/api/report/upcallreport",{"now_date":now_date},function(json){
        console.log('更新时间'+json.data.update_time);
        console.log(json.data.task_state);
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 自动填表
$(document).on("click","#tb-sub",function(){
    var city_name = $('#tb_city').val();
    var now_date = $('#tb-date').val();
    loading_img('load','执行中～');
    $.getJSON("/api/report/autooutputxl",{"now_date":now_date,"city_name":city_name},function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});
// 自动填表(临时)
$(document).on("click","#tb1-sub",function(){
    var city_name = $('#tb1_city').val();
    var now_date = $('#tb1-date').val();
    loading_img('load','执行中～');
    $.getJSON("/api/report/autooutputxl",{"now_date":now_date,"city_name":city_name,"is_temp":true},function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});

// 更新电话购情况
$(document).on("click","#update_lx",function(){
    var city_name = $('#lx_city').val();
    loading_img('load','执行中～');
    $.getJSON("/api/report/update_lx",{"city_name":city_name},function(json){
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});

// 可视化图表
function echarts(){
    $('#rightShow').html('<button id="up_echarts">刷新</button><iframe src="/echarts/" frameborder="0" id="iframe"></iframe>');
};
$(document).on("click","#up_echarts",function(){
    loading_img('load','执行中～');
    $.getJSON("/api/report/upecharts",function(json){
        echarts();
        loading_img();
    }).fail(function(){
        alert('出错了~');
        loading_img();
    });
});

// 点击拷贝表格数据
function copy_tb(){
    if($('#rightShow tr').length > 0){
        var res = confirm('是否插入至剪贴板？（需要浏览器支持并给予访问权限）');
        if(res == true){
            var copy_text = '';
            $('#rightShow tr').each(function(){
            $(this).children('th,td').each(function(){  // 遍历 tr 的各个 td
                copy_text += $(this).text().replace('\n','')+'\t';
                });
            copy_text += '\n';
            });
            navigator.clipboard.writeText(copy_text);
            };
    }else{
        alert('未找到可复制的表格~');
    }
    
};

// tabs栏插入
function ins_newtab(tab_name,show_name){
    var is_tab = true;
    $("#tabs li").each(function(){
        var this_name = $(this).attr('tab');
        if (this_name==tab_name) {//如果有同名tab
            if ($(this).hasClass('activate')) {
                ;
            } else {
                $(this).toggleClass('activate');
            };
            is_tab = false;
        } else{
            $(this).removeAttr('class');
        };
    });
    if (is_tab) {
        $("#tabs").append("<li class='activate' tab='"+tab_name+"'><a>"+show_name+"</a><span></span></li>");
        $(".page").hide();
        $("#show-page").append("<div class='page' tab='"+tab_name+"'></div>");
        return true;
    };
    $(".page").hide();
    $("[tab='"+tab_name+"']").show();
    return false;
};
// tab切换
$(document).on("click","#tabs li a",function(){
    // 执行对应的方法
    ins_newtab($(this).parent().attr('tab'));
});
// tab删除
$(document).on("click","#tabs li span",function(){
    // 执行对应的方法
    var tab_name = $(this).parent().attr('tab');
    // console.log(tab_name);
    $("[tab='"+tab_name+"']").remove();//删除对应的page页面和tab
    ins_newtab('index');//回到主页
    // e.stopPropagation();   //表示阻止向父元素冒泡
});

var config_vars = {};

$(document).ready(function(){
    $('.page[tab="index"]').load('/statics/page/index.html');
    index_get_team();
});
